<template>
    <div>
        <div class="i-layout-page-header">
            <PageHeader class="product_tabs" hidden-breadcrumb>
                <div slot="title">
                    <router-link :to="{ path: '/admin/marketing/invitingGroups/index' }"
                    ><Button icon="ios-arrow-back" size="small" class="mr20"
                        >返回</Button
                    ></router-link
                    >
                    <span
                    v-text="$route.params.id ? '编辑活动' : '新建活动'"
                    class="mr20"
                    ></span>
                </div>
            </PageHeader>
        </div>
        <Card :bordered="false" dis-hover class="ivu-mt">
            <Form :model="formData" :label-width="150">
                <FormItem label="活动名称：">
                    <Input v-model="formData.name" placeholder="请输入活动名称" style="width: 30%"></Input>
                </FormItem>
                <FormItem label="发放时间："> 
                    <DatePicker
                        :value="datetime"
                        :editable="false"
                        type="datetimerange"
                        placeholder="在这个时间内登录发放"
                        @on-change="dateChange"
                        style="width: 30%"
                    ></DatePicker>
                </FormItem>
                <FormItem prop="image">
                    <div class="custom-label" slot="label">
                        <div>
                        <div>社群二维码</div>
                        </div>
                        <div>：</div>
                    </div>
                    <div class="picBox" @click="modalPicTap2('dan', 'danFrom')">
                        <div class="pictrue" v-if="formData.qrcode">
                        <img v-lazy="formData.qrcode" />
                        </div>
                        <div class="upLoad acea-row row-center-wrapper" v-else>
                        <Icon type="ios-camera-outline" size="26" class="iconfonts" />
                        </div>
                    </div>
                </FormItem>
                <!-- <FormItem label="有效天数：">
                    <InputNumber
                        :min="1"
                        v-model="formData.store_num"
                        :precision="0"
                    ></InputNumber>
                </FormItem> -->
                <FormItem label="规格选择：" prop="prize">
                  <Table
                    :data="specsData"
                    :columns="columns"
                    border
                    :draggable="true"
                  >
                    <template slot-scope="{ row, index }" slot="image">
                        <div
                            class="acea-row row-middle row-center-wrapper"
                            @click="modalPicTap('dan', 'goods', index)"
                        >
                            <div class="pictrue pictrueTab" v-if="row.image">
                                <img v-lazy="row.image" />
                            </div>
                            <div
                            class="upLoad pictrueTab acea-row row-center-wrapper"
                            v-else
                            >
                                <Icon
                                    type="ios-camera-outline"
                                    size="21"
                                    class="iconfonts"
                                />
                            </div>
                        </div>
                    </template>
                    <template slot-scope="{ row, index }" slot="name">
                        <Input v-model="specsData[index].name" placeholder="请输入奖品名称" style="width: 80%"></Input>
                    </template>
                    <template slot-scope="{ row, index }" slot="num">
                        <InputNumber
                            v-model="row.num"
                            :max="99999"
                            :min="0"
                            :precision="0"
                            class="priceBox"
                            @on-change="
                            (data) => {
                                changeTotal2(data, index);
                            }
                            "
                        ></InputNumber>
                    </template>
                    <template slot-scope="{ row, index }" slot="encourage">
                        <div>
                            <RadioGroup v-model="specsData[index].type">
                                <Radio :label="1">积分</Radio>
                                <Radio :label="2">优惠券</Radio>
                                <Radio :label="3">卡包</Radio>
                            </RadioGroup>
                            <template v-if="specsData[index].type == 1">
                                <InputNumber
                                    v-model="specsData[index].total"
                                    :max="99999"
                                    :min="0"
                                    :precision="0"
                                    class="priceBox"
                                    style="width: 100%"
                                    placeholder="请输入积分"
                                ></InputNumber>
                            </template>
                            <template v-if="specsData[index].type == 2">
                                <Select v-model="specsData[index].coupon_id" style="width: 100%" placeholder="请选择优惠券">
                                    <Option v-for="item in categoryList" :value="item.id" :key="item.id">
                                        {{ item.title }}
                                    </Option>
                                </Select>
                            </template>
                            <template v-if="specsData[index].type == 3">
                                <Select v-model="specsData[index].card_pack_id" style="width: 100%" placeholder="请选择卡包">
                                    <Option v-for="item in kaList" :value="item.pid" :key="item.pid">
                                        {{ item.title }}
                                    </Option>
                                </Select>
                            </template>
                        </div>
                    </template>
                    <template slot-scope="{ row, index }" slot="setting">
                        <Button class="submission mr15" @click="editGoods(index)"
                            >删除</Button
                        >
                    </template>
                    </Table>
                    <Button
                        type="primary"
                        class="submission mr15 mt20"
                        @click="addGoods"
                        >添加商品</Button
                    >
                </FormItem>
                <FormItem label="活动描述：" prop="">
                    <vue-ueditor-wrap
                        v-model="formData.rule_descr"
                        :key="1"
                        @beforeInit="addCustomDialog"
                        :config="myConfig"
                        style="width: 90%"
                    ></vue-ueditor-wrap>
                </FormItem>
                <!-- <FormItem label="状态：">
                    <RadioGroup v-model="formData.is_show">
                    <Radio :label="1">开启</Radio>
                    <Radio :label="0">关闭</Radio>
                    </RadioGroup>
                </FormItem> -->
                <FormItem>
                    <Button type="primary" @click="save">立即创建</Button>
                </FormItem>
            </Form>
      </Card>
       <!-- 上传图片-->
        <Modal
            v-model="modalPic"
            width="950px"
            scrollable
            footer-hide
            closable
            title="上传商品图"
            :mask-closable="false"
            :z-index="1"
        >
            <uploadPictures
                :isChoice="isChoice"
                @getPic="getPic"
                v-if="modalPic"
            ></uploadPictures>
        </Modal>
        <Modal
            v-model="modalPic2"
            width="950px"
            scrollable
            footer-hide
            closable
            title="上传商品图"
            :mask-closable="false"
            :z-index="1"
            >
            <uploadPictures
                :isChoice="isChoice"
                @getPic="getPic2"
                v-if="modalPic2"
            ></uploadPictures>
        </Modal>
    </div>
</template>

<script>
  import { cardListApi,activityAdd,activityEdit,activityEetail } from "@/api/marketing";
  import { couponApi } from "@/api/user";
  import VueUeditorWrap from "vue-ueditor-wrap";
  import uploadPictures from "@/components/uploadPictures";
  export default{
    name: "invitingGroupsCreate",
    components: {
        VueUeditorWrap,
        uploadPictures
    },
    data(){
        return {
            modalPic: false,
            modalPic2: false,
            datetime: [],
            formData: {
                name: "", //标题
                start_time: "", //开始时间
                end_time: "", //结束时间
                rule_descr: "", //规则描述
                prize:[],
                qrcode: "", //群二维码
            },
            myConfig: {
                autoHeightEnabled: false, // 编辑器不自动被内容撑高
                initialFrameHeight: 500, // 初始容器高度
                initialFrameWidth: "100%", // 初始容器宽度
                UEDITOR_HOME_URL: "/admin/UEditor/",
                serverUrl: "",
            },
            specsData: [
                {
                    type: 1, //奖品类型
                    coupon_id: '', //优惠券id
                    card_pack_id: '', //卡包id
                    name: "", //活动名称
                    total: 0, //积分
                    num: 0, //达标数
                    image: "", //奖品图片
                    sort: 1, //排序
                },
            ],
            prize: [], //奖品数组
            columns: [
                {
                    title: "序号",
                    type: "index",
                    width: 60,
                    align: "center",
                },
                {
                    title: "图片",
                    slot: "image",
                    align: "center",
                    minWidth: 120,
                },
                {
                    title: "奖品名称",
                    slot: "name",
                    align: "center",
                    minWidth: 80,
                },
                {
                    title: "奖品",
                    slot: "encourage",
                    align: "center",
                    minWidth: 80,
                },
                {
                    title: "达标人数",
                    slot: "num",
                    align: "center",
                    minWidth: 80,
                },
                {
                    title: "操作",
                    slot: "setting",
                    align: "center",
                    minWidth: 80,
                },
            ],
            categoryList:[],
            kaList:[],
        }
    },
    created() {
        this.getList();
        if (this.$route.params.id) {
            this.getCouponDetail();
        }
    },
    methods:{
        getList() {
            let tableFrom = {
                is_show: 1,
                issue_type: 1,
            };
            cardListApi(tableFrom).then(async (res) => {
                this.kaList = res.data.list;
                }).catch((res) => {
                this.$Message.error(res.msg);
                });
            couponApi(this.page).then(async res => {
                if (res.status === 200) {
                    let data = res.data
                    this.categoryList = data.list;
                } else {
                    this.$Message.error(res.msg);
                }
            }).catch(res => {
                this.$Message.error(res.msg);
            })                
        },
         // 详情
        getCouponDetail() {
            activityEetail(this.$route.params.id)
                .then((res) => {
                    let data = res.data;
                    this.formData.name = data.name;
                    this.formData.start_time = data.start_time;
                    this.formData.end_time = data.end_time;
                    this.datetime = [data.start_time, data.end_time];
                    this.formData.rule_descr = data.rule_descr;
                    this.formData.prize = data.prize;
                    this.formData.qrcode = data.qrcode;
                    this.specsData = data.prize;
                })
                .catch((err) => {
                    this.$Message.error(err.msg);
                });
        },

        // 新增
        addGoods(){
            console.log(this.specsData)
            this.specsData.push({
                type: 1, // 奖品类型
                coupon_id: '', // 优惠券id
                card_pack_id: '', // 卡包id
                name: '', // 活动名称
                total: 0, // 积分
                num: 0, // 达标数
                image: "", // 奖品图片
                sort: 1,
            });
        },
        // 删除
        editGoods(index){
            this.specsData.splice(index, 1);
        },
        dateChange(time) {
            this.formData.start_time = time[0];
            this.formData.end_time = time[1];
        },
        // 点击商品图
        modalPicTap(tit, picTit, index) {
            this.modalPic = true;
            this.isChoice = tit === "dan" ? "单选" : "多选";
            this.picTit = picTit || "";
            this.tableIndex = index;
        },
        // 点击商品图
        modalPicTap2(tit, picTit, index) {
            this.modalPic2 = true;
            this.isChoice = tit === "dan" ? "单选" : "多选";
            this.picTit = picTit;
            this.tableIndex = index;
        },
        // 获取单张图片信息
        getPic(pc) {
            switch (this.picTit) {
                case "danFrom":
                this.formValidate.image = pc.att_dir;
                break;
                default:
                this.specsData[this.tableIndex].image = pc.att_dir;
            }
            this.modalPic = false;
        },
        getPic2(pc) {
            switch (this.picTit) {
                case "danFrom":
                this.formData.qrcode = pc.att_dir;
                break;
                // case 'danTable':
                //     this.specsData[this.tableIndex].pic = pc.att_dir;
                //     break;
                default:
                if (!!this.formData.attrs && this.formData.attrs.length) {
                    this.$set(this.specsData[this.tableIndex], "_checked", true);
                }
                this.specsData[this.tableIndex].pic = pc.att_dir;
            }
            this.modalPic2 = false;
        },
        changeTotal2(data, index) {
            this.$set(this.specsData[index], "num", data);
        },
        // 添加自定义弹窗
        addCustomDialog(editorId) {
            window.UE.registerUI(
            "test-dialog",
            function(editor, uiName) {
                // 创建 dialog
                let dialog = new window.UE.ui.Dialog({
                // 指定弹出层中页面的路径，这里只能支持页面，路径参考常见问题 2
                    iframeUrl: "/admin/widget.images/index.html?fodder=dialog",
                    // 需要指定当前的编辑器实例
                    editor: editor,
                    // 指定 dialog 的名字
                    name: uiName,
                    // dialog 的标题
                    title: "上传图片",
                    // 指定 dialog 的外围样式
                    cssRules: "width:1200px;height:500px;padding:20px;",
                });
                this.dialog = dialog;
                    var btn = new window.UE.ui.Button({
                        name: "dialog-button",
                        title: "上传图片",
                        cssRules: `background-image: url(../../../assets/images/icons.png);background-position: -726px -77px;`,
                        onclick: function() {
                            // 渲染dialog
                            dialog.render();
                            dialog.open();
                        },
                    });
                    return btn;
                },
            );
        },
        // 创建
        save() {
            for(let i=0; i<this.specsData.length; i++){
                if(this.specsData[i].type == 1){
                    this.specsData[i].coupon_id = ''
                    this.specsData[i].card_pack_id = ''
                }else if(this.specsData[i].type == 2){
                    this.specsData[i].card_pack_id = ''
                    this.specsData[i].total = 0
                }else if(this.specsData[i].type == 3){
                    this.specsData[i].coupon_id = ''
                    this.specsData[i].total = 0
                }
            }
            this.formData.prize = this.specsData
            console.log(this.formData,"1111")
                // if (!this.formData.title) {
                //     return this.$Message.error("请输入卡包名称");
                // }
                let id = 0;
                if (this.$route.params.id) {
                    id = this.$route.params.id;
                    activityEdit(this.formData,id)
                    .then((res) => {
                        this.$Message.success(res.msg);
                        setTimeout(() => {
                        this.$router.push({
                            path: "/admin/marketing/invitingGroups/index",
                        });
                        }, 1000);
                    })
                    .catch((err) => {
                        this.$Message.error(err.msg);
                    });
                }else{
                    activityAdd(this.formData)
                    .then((res) => {
                        this.$Message.success(res.msg);
                        setTimeout(() => {
                        this.$router.push({
                            path: "/admin/marketing/invitingGroups/index",
                        });
                        }, 1000);
                    })
                    .catch((err) => {
                        this.$Message.error(err.msg);
                    });
                }
            
            }
        }
    }
</script>


<style scoped lang="stylus">
  .pictrue {
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0, 0, 0, 0.1);
    margin-right: 15px;
    display: inline-block;
    position: relative;
    cursor: pointer;

    img {
      width: 100%;
      height: 100%;
    }

    .btndel {
      position: absolute;
      z-index: 9;
      width: 20px !important;
      height: 20px !important;
      left: 46px;
      top: -4px;
    }
  }
  .custom-label {
    display: inline-flex;
    line-height: 1.5;
  }
  .picBox {
    display: inline-block;
    cursor: pointer;
  }
</style>
